#include "adminmainwindow.h"
#include "mainwindow.h"
#include "logindialog.h"
#include "sqloperator.h"
#include "adminmainwindow.h"
#include "adminmanager.h"
#include <QApplication>
#include <QCoreApplication>
#include <QFile>
#include <QMessageBox>
#include <QDebug>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    // 加载样式表
    QFile styleFile("c:/Users/23856/OneDrive/Desktop/user2/aaa/stylesheet.qss");
    if (styleFile.open(QFile::ReadOnly)) {
        QString styleSheet = QLatin1String(styleFile.readAll());
        a.setStyleSheet(styleSheet);
        styleFile.close();
    } else {
        qWarning() << "无法打开样式表文件: " << styleFile.errorString();
    }

    // 初始化数据库
    SqlOperator dbOperator;
    // 使用应用程序目录构建数据库路径
    QString appDir = QCoreApplication::applicationDirPath();
    QString dbPath = appDir + "/../../sql/company.db";
    if (!dbOperator.open(dbPath, "loginConnection")) {
        QMessageBox::critical(nullptr, "数据库错误", "无法连接到数据库: " + dbOperator.lastError());
        return -1;
    }

    // 显示登录对话框
    LoginDialog loginDialog(&dbOperator);
    if (loginDialog.exec() != QDialog::Accepted) {
        dbOperator.close();
        return 0;
    }
    // 登录成功后不再关闭数据库连接，由程序退出时统一关闭

    // 根据用户角色显示不同的窗口
    QString userRole = loginDialog.getUserRole();
    QMainWindow *mainWindow = nullptr;

    if (userRole == "admin") {
        AdminMainWindow *adminWindow = new AdminMainWindow;
        // 使用现有的数据库连接
        AdminManager *adminManager = new AdminManager(&dbOperator);
        adminWindow->setAdminManager(adminManager);
        mainWindow = adminWindow;
    } else if (userRole == "employee") {
        MainWindow *employeeWindow = new MainWindow;
        // 设置员工ID
        employeeWindow->setEmployeeId(loginDialog.getEmployeeId());
        mainWindow = employeeWindow;
    } else {
        QMessageBox::warning(nullptr, "登录错误", "未知的用户角色: " + userRole);
        dbOperator.close();
        return -1;
    }

    // 设置窗口在关闭时自动删除
    mainWindow->setAttribute(Qt::WA_DeleteOnClose);
    mainWindow->show();

    int result = a.exec();

    // 在程序退出前关闭数据库连接
    dbOperator.close();
    return result;
}
